<template>
	<div class="system-notice">
		<div class="notice-content">
			<el-table ref="noticeTable" v-loading="loading" :data="noticeList" v-if="noticeList[0]"
				@selection-change="handleSelectionChange" 
				@mouseover.native="stopScroll"
				@mouseout.native="startScroll"
				:height="tableHeight">
				<!-- <el-table-column label="序号" align="center" prop="noticeId" width="100" /> -->
				<el-table-column label="公告标题" align="left" prop="noticeTitle" :show-overflow-tooltip="true">
					<template slot-scope="scope">
						<a href="javascript:void(0)" @click="handleView(scope.row)">{{ scope.row.noticeTitle }}</a>
					</template>
				</el-table-column>
				<el-table-column label="公告类型" align="center" prop="noticeType" width="100">
					<template slot-scope="scope">
						<dict-tag :options="dict.type.sys_notice_type" :value="scope.row.noticeType" />
					</template>
				</el-table-column>
				<el-table-column label="发布时间" align="center" prop="createTime">
					<template slot-scope="scope">
						<span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
					</template>
				</el-table-column>
			</el-table>
			<el-empty v-else
				image="https://zhinengsuo-1305759786.cos.ap-guangzhou.myqcloud.com/pc/tableNoData.73c949f3.png"></el-empty>
		</div>

		<!-- 查看公告详情对话框 -->
		<el-dialog title="公告详情" :visible.sync="openView" width="780px" append-to-body>
			<div v-if="form.noticeTitle" class="notice-detail">
				<h2 class="notice-title">{{ form.noticeTitle }}</h2>
				<div class="notice-meta">
					<span>发布时间：{{ parseTime(form.createTime) }}</span>
					<span style="margin-left: 20px;">公告类型：
						<dict-tag :options="dict.type.sys_notice_type" :value="form.noticeType" />
					</span>
				</div>
				<div v-if="form.titleImg" class="notice-image">
					<img :src="form.titleImg" alt="公告图片" style="max-width: 100%;">
				</div>
				<div class="notice-content" v-html="form.noticeContent"></div>
			</div>
			<div slot="footer" class="dialog-footer">
				<el-button @click="openView = false">关 闭</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import {
		listNotice,
		getNotice,
		delNotice,
		addNotice,
		updateNotice
	} from "@/api/system/notice";
	import {
		deptTreeSelect1
	} from "@/api/system/user";
	import Treeselect from "@riophae/vue-treeselect";
	import "@riophae/vue-treeselect/dist/vue-treeselect.css";
	export default {
		name: "Notice",
		dicts: ['sys_notice_status', 'sys_notice_type'],
		components: {
			Treeselect
		},
		data() {
			return {
				tableHeight: 350, // 表格高度调整为适合卡片
				scrollTimer: null, // 滚动定时器
				currentIndex: 0, // 当前滚动位置
				scrollStep: 0.5, // 减小滚动步长，使滚动更平滑
				scrollInterval: 30, // 减小滚动间隔，增加滚动平滑度
				autoScrollbar: {
					time: 1000 * 60,
					speed: 1000 * 60,
					loop: false,
					timeLoop: true,
				},
				deptOptions: null,
				// 遮罩层
				loading: true,
				// 选中数组
				ids: [],
				// 非单个禁用
				single: true,
				// 非多个禁用
				multiple: true,
				// 显示搜索条件
				showSearch: true,
				// 总条数
				total: 0,
				// 公告表格数据
				noticeList: [],
				// 弹出层标题
				title: "",
				// 是否显示弹出层
				open: false,
				// 是否显示查看详情弹出层
				openView: false,
				// 查询参数
				queryParams: {
					pageNum: 1,
					pageSize: 10,
					noticeTitle: undefined,
					createBy: undefined,
					status: "0", // 默认查询已发布的公告
				},
				// 表单参数
				form: {},
				// 表单校验
				rules: {
					noticeTitle: [{
						required: true,
						message: "公告标题不能为空",
						trigger: "blur"
					}],
					noticeType: [{
						required: true,
						message: "公告类型不能为空",
						trigger: "change"
					}],
					deptId: [{
						required: true,
						message: "归属部门不能为空",
						trigger: "change"
					}]
				}
			};
		},
		created() {
			this.getList();
			this.getDeptTree();
		},
		mounted() {
			this.startScroll();
		},
		beforeDestroy() {
			this.stopScroll();
		},
		methods: {
			getDeptTree() {
				deptTreeSelect1().then(response => {
					this.deptOptions = response.data;
				});
			},
			/** 查询公告列表 */
			getList() {
				this.loading = true;
				listNotice(this.queryParams).then(response => {
					this.noticeList = response.rows;
					this.total = response.total;
					this.loading = false;
				});
			},
			// 取消按钮
			cancel() {
				this.open = false;
				this.reset();
			},
			// 表单重置
			reset() {
				this.form = {
					noticeId: undefined,
					noticeTitle: undefined,
					noticeType: undefined,
					noticeContent: undefined,
					status: "0",
					titleImg: undefined,
				};
				this.resetForm("form");
			},
			/** 搜索按钮操作 */
			handleQuery() {
				this.queryParams.pageNum = 1;
				this.getList();
			},
			/** 重置按钮操作 */
			resetQuery() {
				this.resetForm("queryForm");
				this.handleQuery();
			},
			// 多选框选中数据
			handleSelectionChange(selection) {
				this.ids = selection.map(item => item.noticeId)
				this.single = selection.length != 1
				this.multiple = !selection.length
			},
			/** 新增按钮操作 */
			handleAdd() {
				this.reset();
				this.open = true;
				this.title = "添加公告";
			},
			/** 修改按钮操作 */
			handleUpdate(row) {
				this.reset();
				const noticeId = row.noticeId || this.ids
				getNotice(noticeId).then(response => {
					this.form = response.data;
					this.open = true;
					this.title = "修改公告";
				});
			},
			/** 查看公告详情 */
			handleView(row) {
				this.reset();
				const noticeId = row.noticeId;
				getNotice(noticeId).then(response => {
					this.form = response.data;
					// 添加日志，帮助调试
					console.log("公告详情数据:", this.form);
					this.openView = true;
				}).catch(error => {
					console.error("获取公告详情失败:", error);
					this.$message.error("获取公告详情失败，请稍后重试");
				});
			},
			/** 提交按钮 */
			submitForm: function() {
				this.$refs["form"].validate(valid => {
					if (valid) {
						if (this.form.noticeId != undefined) {
							updateNotice(this.form).then(response => {
								this.$modal.msgSuccess("修改成功");
								this.open = false;
								this.getList();
							});
						} else {
							addNotice(this.form).then(response => {
								this.$modal.msgSuccess("新增成功");
								this.open = false;
								this.getList();
							});
						}
					}
				});
			},
			/** 删除按钮操作 */
			handleDelete(row) {
				const noticeIds = row.noticeId || this.ids
				this.$modal.confirm('是否确认删除公告编号为"' + noticeIds + '"的数据项？').then(function() {
					return delNotice(noticeIds);
				}).then(() => {
					this.getList();
					this.$modal.msgSuccess("删除成功");
				}).catch(() => {});
			},
			// 开始滚动
			startScroll() {
				if (this.scrollTimer) {
					clearInterval(this.scrollTimer);
				}
				this.scrollTimer = setInterval(() => {
					const table = this.$refs.noticeTable;
					if (!table || !table.$el) return;
					
					const body = table.$el.querySelector('.el-table__body-wrapper');
					if (!body) return;

					// 平滑滚动效果
					if (body.scrollTop >= (body.scrollHeight - body.clientHeight)) {
						// 如果滚动到底部，平滑回到顶部
						this.smoothScrollTo(body, 0);
					} else {
						// 平滑滚动一小段距离
						body.scrollTop += this.scrollStep;
					}
				}, this.scrollInterval);
			},
			// 停止滚动
			stopScroll() {
				if (this.scrollTimer) {
					clearInterval(this.scrollTimer);
					this.scrollTimer = null;
				}
			},
			// 平滑滚动到指定位置
			smoothScrollTo(element, position, duration = 500) {
				const start = element.scrollTop;
				const change = position - start;
				const startTime = performance.now();
				
				function animateScroll(currentTime) {
					const elapsedTime = currentTime - startTime;
					if (elapsedTime < duration) {
						// 使用easeInOutQuad缓动函数
						const time = elapsedTime / duration;
						const newPosition = start + change * (time < 0.5 ? 2 * time * time : -1 + (4 - 2 * time) * time);
						element.scrollTop = newPosition;
						requestAnimationFrame(animateScroll);
					} else {
						element.scrollTop = position;
					}
				}
				
				requestAnimationFrame(animateScroll);
			}
		}
	};
</script>

<style lang="scss" scoped>
.system-notice {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  padding: 0;
  
  .notice-content {
    flex: 1;
    overflow: hidden;
    
    ::v-deep .el-table {
      background: transparent;
      height: 100%;
      
      .el-table__header-wrapper {
        th {
          padding: 8px 0;
          background-color: #fafafa;
        }
      }
      
      .el-table__body-wrapper {
        overflow-y: hidden;
        
        &::-webkit-scrollbar {
          width: 4px;
        }
        
        &::-webkit-scrollbar-thumb {
          background-color: rgba(144, 147, 153, 0.3);
          border-radius: 2px;
        }
      }
      
      a {
        color: #1890ff;
        text-decoration: none;
        
        &:hover {
          color: #40a9ff;
        }
      }
    }
  }
}

.notice-detail {
  padding: 20px;
  
  .notice-title {
    text-align: center;
    font-size: 18px;
    margin-bottom: 20px;
    color: #303133;
  }
  
  .notice-meta {
    text-align: center;
    color: #909399;
    margin-bottom: 20px;
    font-size: 14px;
  }
  
  .notice-image {
    text-align: center;
    margin-bottom: 20px;
  }
  
  .notice-content {
    line-height: 1.8;
    color: #606266;
  }
}
</style>
